TOPDIR	:= $(shell if [ "$$PWD" != "" ]; then echo $$PWD; else pwd; fi)

HPATH   	= $(TOPDIR)/include

LD	=ld -m elf_i386
CC	=gcc -D__KERNEL__ -I$(HPATH)
CPP	=$(CC) -E
NM	=nm
OBJCOPY =objcopy -O binary -R .note -R .comment -S
LINKFLAGS =-T $(TOPDIR)/kernel.lds

all: vmlinux

CFLAGS = -Wall -g3 -O0 -fomit-frame-pointer -fno-stack-protector -no-pie -fno-pic -m32 -fno-builtin
export TOPDIR CC LD CFLAGS

ARCHIVES=kernel/kernel.o
SUBDIRS	=kernel

zImage: vmlinux boot/bootsect.bin boot/setup.bin
	rm -f zImage
	bximage -mode=create -fd=1.44M -q zImage
	$(OBJCOPY) vmlinux vmlinux.out
	dd if=boot/bootsect.bin of=zImage bs=512 count=1 conv=notrunc status=none
	dd if=boot/setup.bin of=zImage bs=512 count=4 seek=1 conv=notrunc status=none
	dd if=vmlinux.out of=zImage bs=512 count=1024 seek=5 conv=notrunc status=none

vmlinux: kernel/head.o init/main.o linuxsubdirs
	$(LD) $(LINKFLAGS) kernel/head.o init/main.o	\
		--start-group	\
		$(ARCHIVES)	\
		--end-group	\
		-o vmlinux
	$(NM) vmlinux | grep -v '\(compiled\)\|\(\.o$$\)\|\( [aU] \)\|\(\.\.ng$$\)\|\(LASH[RL]DI\)' | sort > System.map

boot/%.bin: boot/%.S
	$(CPP) -traditional $< -o boot/$*.s
	nasm -o $@ boot/$*.s

kernel/head.o: kernel/head.S
	$(CC) -D__ASSEMBLY__ -m32 -traditional -c kernel/head.S -o kernel/head.o

linuxsubdirs:
	set -e; for i in $(SUBDIRS); do $(MAKE) -C $$i; done

init/main.o: init/main.c
	$(CC) $(CFLAGS) -c -o $*.o $<

run: zImage
	qemu-system-i386 -m 2048 -k en-us -rtc base=localtime -device cirrus-vga -fda zImage -boot a

qemu: zImage
	qemu-system-i386 -m 2048 -k en-us -rtc base=localtime -device cirrus-vga -fda zImage -boot a -s -S

gdb:
	gdb vmlinux -n -x .gdbinit

clean:
	rm -f core `find . -name '*.[oas]' -print`
	rm -rf boot/*.bin vmlinux.out zImage
	rm -rf vmlinux System.map

